<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="addRoleBtn"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="roleList">
              <el-table-column label="序号" width="120" type="index">
                <template #default="{$index}">

                  {{ (page.page -1) * page.pagesize + $index + 1 }}

                </template>
              </el-table-column>
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="assignPermission(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRoleBtn(row.id)">删除</el-button>
                </template>

              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next"
                :total="page.total"
                :page-size="page.pagesize"
                :current-page="page.page"
                @current-change="changeCurrent"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>

        </el-tabs>
      </el-card>
      <!-- 弹窗 -->
      <el-dialog :title="`${title}弹层`" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <el-dialog title="分配权限" :visible="assignPerm" @close="btnPerCannel">
        <el-tree
          ref="assignPermission"
          :data="PermList"
          :props="{label:'name'}"
          default-expand-all
          show-checkbox
          check-strictly
          node-key="id"
        />
        <template #footer>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" @click="btnPerCannel">取消</el-button>
              <el-button size="small" type="primary" @click="btnPerOK">确定</el-button>
            </el-col>
          </el-row>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { companyQuery, roleListAPI, delRole, updataRole, roleDetails, addRole, assignRole } from '@/api/setting'
import { GetAllPermission } from '@/api/permission'
import { listToTreeData } from '@/utils/index'
export default {
  data() {
    return {
      formData: {
        name: '',
        remarks: '',
        mailbox: '',
        companyAddress: ''
      },
      roleList: [],
      page: {
        page: 1,
        pagesize: 2,
        total: 0
      },
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '不能为空', tigger: 'blur' }
        ],
        description: [
          { required: true, message: '不能为空', tigger: 'blur' }
        ]
      },
      showDialog: false,
      assignPerm: false,
      PermList: [],
      roleId: ''
    }
  },
  computed: {
    title() {
      return this.roleForm.id ? '编辑' : '添加'
    }
  },
  created() {
    this.companyQuery()
    this.roleListAPI()
    this.GetAllPermission()
  },
  methods: {
    // 关闭弹窗
    btnPerCannel() {
      this.$refs.assignPermission.setCheckedKeys([])
      this.assignPerm = false
    },
    async  btnPerOK() {
      await assignRole({
        id: this.roleId,
        permIds: this.$refs.assignPermission.getCheckedKeys()
      })
      this.$message.success('操作成功')
      // this.GetAllPermission()
      this.assignPerm = false
    },
    // 获取所有权限
    async GetAllPermission() {
      const res = await GetAllPermission()
      console.log(res)
      this.PermList = listToTreeData(res.filter(it => it.enVisible === '1'), '0')
    },
    // 分配权限
    async assignPermission(id) {
      this.roleId = id
      const { permIds } = await roleDetails(id)
      this.assignPerm = true
      this.$nextTick(() => {
        this.$refs.assignPermission.setCheckedKeys(permIds)
      })
      // console.log(res)
    },
    // 查询企业根据ID
    async  companyQuery() {
      const res = await companyQuery(this.$store.state.user.userInfo.companyId)
      this.formData = res
    },
    // 获取所有角色列表
    async roleListAPI() {
      const { rows, total } = await roleListAPI(this.page)
      // console.log(rows, total)
      this.roleList = rows
      this.page.total = total
    },
    // 页面发生变化触发
    async changeCurrent(index) {
      // 重新获取当前页的数据
      this.page.page = index
      await this.roleListAPI()
    },
    // 删除角色
    async delRoleBtn(id) {
      try {
        // 二次确认
        await this.$confirm('是否确认删除？？？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        //  发送请求
        await delRole(id)
        // 提示用户
        this.$message.success('删除成功')
        // 更新数据
        if (this.roleList.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        this.roleListAPI()
      } catch (error) {
        console.log(error)
      }
    },
    // 取消按钮和关闭弹窗
    btnCancel() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 确认按钮
    async  btnOK() {
      try {
        // 校验
        await this.$refs.roleForm.validate()
        // 发送请求
        if (this.roleForm.id) {
          // 编辑
          await updataRole(this.roleForm)
        } else {
          // 新增
          await addRole(this.roleForm)
        }
        // 提示用户
        this.$message.success('操作成功')
        // 关闭弹窗
        this.showDialog = false
        // 更新数据
        await this.roleListAPI()

        this.page.page = Math.ceil(this.page.total / this.page.pagesize)
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑角色
    async  editRole(id) {
      this.showDialog = true
      this.roleForm = await roleDetails(id)
      // console.log(this.roleForm)
    },
    // 添加角色
    addRoleBtn() {
      this.showDialog = true
    }

  }
}
</script>

<style>

</style>
